// go语言切片(Slice)
package main

import "fmt"

/**
 * 定义切片
 * 1.var identifier []type
 * 2.var slice1 []type = make([]type, len)
 * 3.slice1 := make([]type, len)
 * 4.make([]T, length, capacity)
 * len()和cap()函数
 */
func t1() {
	var numbers = make([]int, 3, 5)
	printSlice(numbers)
}
func printSlice(x []int) {
	fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x)
}

/**
 * 空切片
 */
func t2() {
	var numbers []int
	printSlice(numbers)
	if numbers == nil {
		fmt.Println("切片是空的")
	}
}

/**
 * 切片截取[low-bound: upper-bound)左闭右开
 */
func t3() {
	numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
	printSlice(numbers)

	fmt.Println("numbers ==", numbers)
	fmt.Println("numbers[1:4] ==", numbers[1:4])
}

/**
 * append()和copy()函数
 */
func t4() {
	var numbers []int
	printSlice(numbers)

	// 追加空切片
	numbers = append(numbers, 0)
	printSlice(numbers)

	// 向切片添加一个元素
	numbers = append(numbers, 1)
	printSlice(numbers)

	// 向切片添加多个元素
	numbers = append(numbers, 2, 3, 4)
	printSlice(numbers)

	// 扩容
	numbers1 := make([]int, len(numbers), (cap(numbers))*2)
	copy(numbers1, numbers)
	printSlice(numbers1)
}

func main() {
	t1()
	t2()
	t3()
	t4()
}
